package com.ytjj.qmyx.supplychain.service;

import com.github.pagehelper.PageHelper;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.enums.ProductStatusEnums;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.request.BankerApplyRequest;
import com.ytjj.qmyx.supplychain.common.model.response.BankerApplyResponse;
import com.ytjj.qmyx.supplychain.mapper.BankerApplyMapper;
import com.ytjj.qmyx.supplychain.mapper.BankerMessageMapper;
import com.ytjj.qmyx.supplychain.mapper.BankerProductMapper;
import com.ytjj.qmyx.supplychain.mapper.ProductMapper;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBankerApply;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBankerMessage;
import com.ytjj.qmyx.supplychain.mapper.entity.YxBankerProduct;
import com.ytjj.qmyx.supplychain.mapper.entity.YxProduct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * 
 * 
 * @Version: 1.0
 */
@Slf4j
@Service
public class BankerApplyService {
    @Resource
    private BankerApplyMapper bankerApplyMapper;
    @Resource
    private BankerProductMapper bankerProductMapper;
    @Resource
    private BankerMessageMapper bankerMessageMapper;
    @Autowired
    private ProductService productService;
    @Resource
    private ProductMapper productMapper;

    public Integer insertApply(YxBankerApply bankerApply) {
        // 先判断是否存在,存在先删除
        if(checkExist(bankerApply.getBankerProductId()) > 0) {
            removeByBankerProductId(bankerApply.getBankerProductId());
        }
        // 否则，增加一条新的数据
        bankerApply.setStatus(1);
        bankerApply.setCreateTime(new Date());
        return bankerApplyMapper.insert(bankerApply);
    }

    public int checkExist(Integer bankerProductId) {
        Example example = new Example(YxBankerApply.class);
        example.createCriteria().andEqualTo("bankerProductId", bankerProductId).andNotEqualTo("status", 1);
        return bankerApplyMapper.selectCountByExample(example);
    }

    public int removeByBankerProductId(Integer bankerProductId) {
        Example example = new Example(YxBankerApply.class);
        example.createCriteria().andEqualTo("bankerProductId", bankerProductId);
        return bankerApplyMapper.deleteByExample(example);
    }

    public CommonPage<BankerApplyResponse> selectList(BankerApplyRequest request) {
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        List<BankerApplyResponse> pageList = bankerApplyMapper.selectList(request);
        return CommonPage.restPage(pageList);
    }

    @Transactional(rollbackFor = Exception.class)
    public void rollBack(Integer bankerProductId, String message) {
        log.info("===打回商品id==={}", bankerProductId);
        YxProduct yxProduct = productMapper.selectByPrimaryKey(bankerProductId);
        if (null == yxProduct) {
            log.info("===找不到需要打回的商品信息==={}", bankerProductId);
        }
        // 打回操作，商品管理status->5
        bankerProductMapper.rollbackSupplyChainProduct(yxProduct.getId(), 5);
        //打回操作，平台商品同步到供应商中
        //查询平台商品信息
        try {
            productService.synriBankerProductInfo(bankerProductId);
        } catch (Exception e) {
            log.info("===同步商品信息到供应商商品信息失败==={}", e);
        }

        // 标记该条申请已完成
//        bankerApplyMapper.applyStatus(bankerProductId, 2);
        YxBankerMessage bankerMessage = new YxBankerMessage();
        bankerMessage.setBankerId(yxProduct.getBankerId());
        bankerMessage.setBankerProductId(yxProduct.getBankerProductId());
        bankerMessage.setRemarks("您的商品id：" + yxProduct.getBankerProductId() + " 现已被打回,请及时完善相关信息,原因：(" + message + ")");
        bankerMessage.setStatus(0);
        bankerMessage.setCreateTime(new Date());
        bankerMessageMapper.insert(bankerMessage);
    }

    public void bankerAppRollBack(Integer bankerProductId, String message) {
        YxBankerProduct bankerProduct = bankerProductMapper.selectByPrimaryKey(bankerProductId);
        bankerProduct.setStatus(ProductStatusEnums.DOWN.getStatus().byteValue());
        bankerProductMapper.updateByPrimaryKey(bankerProduct);
        Example example = new Example(YxProduct.class);
        example.createCriteria().andEqualTo("bankerProductId", bankerProductId);
        example.setOrderByClause("id desc limit 1");
        YxProduct product = productMapper.selectOneByExample(example);
        product.setStatus(ProductStatusEnums.DOWN.getStatus().byteValue());
        product.setDownRemark(message);
        int count = productMapper.updateByPrimaryKeySelective(product);
     /*   //调用团购渠道接口，下架团购渠道的商品
        if (count > 0) {
            productService.downProductForTuan(Arrays.asList(product.getId()));
        }*/

        // 标记该条申请已完成
        bankerApplyMapper.applyStatus(bankerProductId, 2);
        YxBankerMessage bankerMessage = new YxBankerMessage();
        bankerMessage.setBankerId(bankerProduct.getBankerId());
        bankerMessage.setBankerProductId(bankerProductId);
        bankerMessage.setRemarks("关于您商品id为：" + bankerProductId + " 的编辑申请，已通过！");
        bankerMessage.setStatus(0);
        bankerMessage.setCreateTime(new Date());
        bankerMessageMapper.insert(bankerMessage);

        try {
            if (null != bankerProductId) {
                log.info("===调用销售端商品下架===", bankerProductId);
                productService.downShopProduct(bankerProductId.toString(),message);
            }
        } catch (Exception e) {
            log.error("===调用销售端下架商品失败==={}", bankerProductId.toString());
        }
    }

    @Transactional(rollbackFor = Exception.class)
    public void removeSupplychainProduct(Integer productId, String message) {
        log.info("===移除供应链商品==={}", productId);
        YxProduct product = productMapper.selectByPrimaryKey(productId);
        if (null == product) {
            return;
        }
        if (ProductStatusEnums.UP.getStatus().equals(product.getStatus().intValue())) {
            throw new ApiException("上架状态不能移除");
        }
        product.setStatus(ProductStatusEnums.DELETE.getStatus().byteValue());
        productMapper.updateByPrimaryKey(product);
        YxBankerProduct bankerProduct = bankerProductMapper.selectByPrimaryKey(product.getBankerProductId());
        if (null == bankerProduct) {
            return;
        }
        bankerProduct.setStatus(ProductStatusEnums.DELETE.getStatus().byteValue());
        bankerProductMapper.updateByPrimaryKey(bankerProduct);
    }

    public void returnBack(Integer bankerProductId, Integer bankerId, String remark) {
        YxBankerMessage bankerMessage = new YxBankerMessage();
        bankerMessage.setBankerId(bankerId);
        bankerMessage.setBankerProductId(bankerProductId);
        bankerMessage.setRemarks("关于您商品id为：" + bankerProductId + "的申请被驳回，原因：(" + remark + ")");
        bankerMessage.setStatus(0);
        bankerMessage.setCreateTime(new Date());
        bankerMessageMapper.insert(bankerMessage);

        // 标记该条申请已驳回
        bankerApplyMapper.applyStatus(bankerProductId, 3);
    }

}
